package com.oa.tools.beans;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.oa.tools.dao.OrgElementDAO;
import com.oa.tools.dao.PersonDAO;
import com.oa.tools.entity.OrgElement;
import com.oa.tools.entity.Person;
import com.oa.tools.utils.SysConfig;

import tk.mybatis.mapper.entity.Example;

@Component
public class MyUserDetailsService implements UserDetailsService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
	PersonDAO personDAO;
	@Autowired
	OrgElementDAO orgElementDAO;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("用户的用户名: {}", username);
        
        // TODO 根据用户名，查找到对应的密码，与权限
        Example example = new Example(Person.class);
        example.createCriteria().andEqualTo("fdLoginName", username).andIsNotNull("fdEmail");//.orEqualTo("fdMobileNo",username);
        Person person =  personDAO.selectOneByExample(example);
        if(person==null) {
        	return null;
        }
        
        OrgElement element = orgElementDAO.selectByPrimaryKey(person.getFdId());
        
        boolean readable = false;
       	String[] readers = SysConfig.getSysArray("可阅读人"); 
       	for(String reader:readers) {
       		if(person.getFdLoginName().equals(reader)) {
       			readable = true;
       			break;
       		}
       	}
       	
       	if(!readable) {
	       	OrgElement pElement = orgElementDAO.selectByPrimaryKey(element.getFdParentid());
	       	String[] readOrgs = SysConfig.getSysArray("可阅读部门"); 
	       	for(String reader:readOrgs) {
	        		if(pElement.getFdName().equals(reader)) {
	        			readable = true;
	        			break;
	        		}
	        }
       	}

       	if(!readable) {
        	return null;
        }
        
        
        String pass = person.getFdPassword();
        // 封装用户信息，并返回。参数分别是：用户名，密码，用户权限
        User user = new User(username, pass,
                            AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
        return user;
  }
}
